<?php

include_once 'RM/system/application/classes/RM/Connector.php';

class RM_Drupal_Connector extends RM_Connector {

    /**
     * Perform user CMS authentication.
     *
     * @param string $username
     * @param string $password
     * @return bool
     */
    function authenticate($username, $password) {
        user_authenticate($username, $password);
    }

    protected function _getExtraPathes() {
        //get path to resmania module
        return array(drupal_get_path('module', 'resmania') . '/classes');
    }

    public function getDefaultUnitListLength() {
        // TODO: Create config
        return '20';
    }

    public function __construct($module) {
        global $base_root;
        $root_path = realpath(".");
        $this->_module = $module;
        //$this->_rootPath =  $_SERVER['DOCUMENT_ROOT'];
        $this->_rootPath = $root_path;
    }

    public function initDB() {
        $this->_config = $this->_getConfig();
        parent::initDB();
    }

    public function initConfig() {
        $this->_locale = $this->_getLocale();
        $this->_router = $this->_getRouter();
        parent::initConfig();
    }

    public function getUser() {
        global $user; //drupal global variables, return current drupal object user
        return new RM_Drupal_User($user);
    }

    public function getLoginStatus() {
        global $user;
        if (isset($user->uid) && $user->uid != 0) {
            return true;
        }
        return false;
    }

    /* (non-PHPdoc)
     * @see system/application/classes/RM/RM_Connector#getLocale()
     */

    protected function _getLocale() {
        //drupal global variables, return current drupal object lang.
        global $language;
        $locale = $language->language;
        $model = new RM_Languages();
        $lang = $model->find($locale)->current();
        return $lang->iso;
    }

    /**
     * Returns array of SQL queries for database installation
     *
     * @return array
     */
    private function getInstallSQL() {
        $filename = 'RM/system/sql/install.sql';
        $sql = explode(";", file_get_contents($filename));
        return $sql;
    }

    /**
     * Returns array of SQL queries for database uninstall
     *
     * @return array
     */
    private function getUninstallSQL() {
        $filename = 'RM/system/sql/uninstall.sql';
        $sql = explode(";", file_get_contents($filename));
        return $sql;
    }

    protected function _getRouter() {
        $router = new RM_Drupal_Controller_Router($this->getModule());
        $router->addRoute('default', new RM_Drupal_Controller_Router_Route(
                        array(
                            'module' => $this->_module,
                            'controller' => 'Index',
                            'action' => 'index',
                        )
        ));
        return $router;
    }

    /**
     * Returns root url to cms
     *
     * @return string
     */
    public function getRootURL() {
        global $base_url;
        return $base_url . '/';
    }

    /**
     * Retuns the User Root URL
     *
     * @return string
     */
    public function getUserRootUrl() {
        $url = url('user/resmania', $options = array('absolute' => TRUE));
        return $url;
    }

    /* (non-PHPdoc)
     * @see system/application/classes/RM/RM_Connector#getConfig()
     */

    protected function _getConfig() {
        //global $db_url; //drupal global variables, return setting to curent drupal db
        $active_db = Database::getConnection();
        $dbconnection = $active_db->getConnectionOptions();
        $db_type = $dbconnection['driver'];
        $username = $dbconnection['username'];
        $password = $dbconnection['password'];
        $server = $dbconnection['host'];
        $database = $dbconnection['database'];

        $configArray = array(
            'webhost' => base_path(),
            'db' => array(
                'driver' => $db_type,
                'adapter' => 'PDO_MYSQL',
                'params' => array(
                    'host' => $server,
                    'username' => $username,
                    'password' => $password,
                    'dbname' => $database,
                )
            )
        );
        $config = new Zend_Config($configArray);
        return $config;
    }

    /* (non-PHPdoc)
     * @see system/application/classes/RM/RM_Connector#installDB()
     *
     * @depreciated
     */
    public function installDB() {
        $sql = $this->getInstallSQL();
        $this->_parseSQL($sql);
        $url = url('admin/resmania', $options = array('absolute' => TRUE));
        drupal_goto($url);
        //drupal_goto('resmania/admin?option=resmania&actions=index&controllers=index');
    }

    /* (non-PHPdoc)
     * @see system/application/classes/RM/RM_Connector#uninstallDB()
     *
     * @depreciated
     */
    public function uninstallDB() {
        $sql = $this->getUninstallSQL();
        $this->_parseSQL($sql);
    }

    /**
     * Invocate sql query - this is only used for the upgrade process
     *
     * @param $sql - sql query
     * @return null
     * @depreciated
     */
    protected function _parseSQL($sql) {
        foreach ($sql as $command) {
            $command = trim($command);
            if ($command != "") {
                //TODO: Drupal use this {} as special chars
                $this->_resmania_db_query($command);
            }
        }
    }

    /*
     * run a query, unfortunalty Drupal7 does not support inserts for SQL so we
     * have to setup using this process and use { } as placeholders but these are
     * also used in JSON for ResMania so we have to use our own query process

     * @depreciated
     */
    private function _resmania_db_query($query) {

        global $dbConnection;

        // check if we already have an active connection
        if (!is_resource($dbConnection->active_db)){
            // make the db connection
            $dbConnection = $this->_dbConnect($dbConnection);
            if (!$dbConnection){
                return false;
            }
        }

        // set the default (good return)
        $result = array("success"=>true, "error" => "");

        switch ($dbConnection->db_type) {
            case 'mysqli' :
                mysqli_select_db($dbConnection->active_db,$dbConnection->database);
                mysqli_query($dbConnection->active_db, $query) or $result = array("success"=>false, "error" => mysqli_error());
                return $result;
                break;
            case 'mysql' :
                mysql_select_db($dbConnection->database, $dbConnection->active_db);
                mysql_query($query, $dbConnection->active_db) or $result = array("success"=>false, "error" => mysql_error());
                return $result;
                break;
        }
    }

    /**
     * Connect to the Drupal DB
     *
     * @param array $dbConnection
     * @return array
     * @depreciated
     */
    private function _dbConnect($dbConnection){

        $dbConnection->db_type = $this->_config['db']['driver'];
        $dbConnection->database = $this->_config['db']['params']['dbname'];

        switch ($db_type){
            case 'mysqli' :
                $dbConnection->active_db = mysqli_connect($server,$username,$password,$database);
                return $dbConnection;
                break;
            case 'mysql' :
                $dbConnection->active_db = mysql_connect($server,$username,$password,$database);
                return $dbConnection;
                break;
            case 'pgsql':
                // we don't currently support PostgreSQL
                return false;
                break;
        }
    }

    /**
     * Returns the CMS Request HTTP object.
     *
     * @param null
     * @return object
     */
    public function getRequestHTTP() {

        // if Drupal is passing variables on the Query string (GET) then we need
        // to extract these here with some pre-processing and add as seperate
        // values to the $_GET array. 
        if (!empty($_GET['q'])) {
            $values = html_entity_decode($_GET['q']);

            $valuesArray  = explode('&', $values);
            $arr  = array();
            $idsFound = false;

            if (!empty($valuesArray)){
                foreach($valuesArray as $val) {
                    $x = explode('=', $val);

                    // if the item is not already in the Query
                    // string then add it to the $_GET array
                    if (!isset($_GET[$x[0]])){
                        // if the query string contains an ids (array) then
                        // we will tidy this in order to stop errors processing
                        if ($x[0]=="ids[]"){
                            $idsFound = true;
                            $ids[] = $x[1];
                        }
                        // only add the item to the $_GET
                        // array if we actually have data in it
                        if (isset($x[1])) {
                            $_GET[$x[0]] = $x[1];
                        }
                    }
                }

                // add the ids array to the $_GET array.
                if ($idsFound){
                    $_GET['ids'] = $ids;
                }
                unset($val, $x, $var);
            }
        }

        $request = new RM_Drupal_Request_Http();
        return $request;
    }

    public function getUsersModel() {
        return new RM_Drupal_Model_Users();
    }

    /* (non-PHPdoc)
     * @see system/application/classes/RM/RM_Connector#getBackendJSFileURLs()
     */

    public function getBackendJSFileURLs() {
        $path = drupal_get_path('module', 'resmania') . '/classes/RM/Drupal/js/back';
        $files = RM_Filesystem::getFiles($path);
        $result = array();
        foreach ($files as $file) {
            $result[] = $path . '/' . $file;
        }
        return $result;
    }

    /**
     * This returns the CMS borders, these are used ensure that the interface is rendered to a size
     * to take into account these settings.
     *
     * @return 	string	JS viewport variables.
     */
    public function getViewPortJsCode() {

        // get the Maximised state...
        $config = new RM_Config;
        $Maximised = $config->getValue('rm_config_admin_gui_maximised');
        if ($Maximised) {
            return "
                RM.ViewPortSize.top = 10;
                RM.ViewPortSize.left = 10;
                RM.ViewPortSize.right = 10;
                RM.ViewPortSize.bottom = 10;
                ";
        } else {
            return "
                RM.ViewPortSize.top = 150;
                RM.ViewPortSize.left = 0;
                RM.ViewPortSize.right = 0;
                RM.ViewPortSize.bottom = 40;
                ";
        }
    }

    public function getAdminRootUrl() {
        //global $base_url;
        $admin_url = url('admin/resmania', $options = array('absolute' => TRUE));
        return $admin_url;
    }

    /**
     * Sets the Drupal page title
     *
     * @param string $title
     */
    public function setPageTitle($title){
        // not yet implemented.
    }

}
